package wqh.modbus;


import cn.tpson.modbus.core.IDataCallBack;
import cn.tpson.modbus.core.ModBusManager;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import wqh.controller.api.GlobalData;
import wqh.domain.*;
import wqh.global.GlobalChannel;
import wqh.global.GlobalChannelData;
import wqh.global.GlobalDevice;
import wqh.pojo.IPConver;
import wqh.service.*;
import wqh.websocket.channel_websocket.ChannelSocketHandler;
import wqh.websocket.device_websocket.DeviceSocketHandler;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class WaterDataCallBack implements IDataCallBack{

    @Autowired
    private ChannelDataService channelDataService;

    @Autowired
    DeviceSocketHandler deviceSocketHandler;

    @Autowired
    ChannelSocketHandler channelSocketHandler;

    @Autowired
    private GeoBuildingService geoBuildingService;

    @Autowired
    private AlarmEventService alarmEventService;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private MapPosService mapPosService;

    @Autowired
    private DeviceService deviceService;



    public void poll(String s, float v, float v1, float v2, float v3) {
        System.out.println("poll: " + (System.currentTimeMillis()/1000));
        ChannelData channelData = new ChannelData(s,v,v1,v2,v3,(int)(System.currentTimeMillis()/1000));
        channelDataService.insertRecord(channelData);

        Map<String ,Object> channelDataMap = new HashMap<String, Object>();
        channelDataMap.put("channel_1",v);
        channelDataMap.put("channel_2",v1);
        channelDataMap.put("channel_3",v2);
        channelDataMap.put("channel_4",v3);
        channelDataMap.put("collect_time",System.currentTimeMillis() / 1000);
        GlobalData.addData(s,channelDataMap);
        Map<String ,Object> channelDataMap2 = new HashMap<String, Object>(channelDataMap);
        GlobalData.addData("127.0.0.1",channelDataMap2);

        Map<String ,Object> map = new HashMap<String, Object>();
        map.put("ip", IPConver.Ip2Int(s));
        map.put("v0",v);
        map.put("v1",v1);
        map.put("v2",v2);
        map.put("v3",v3);
        GlobalChannelData.setChannelDataStr(JSON.toJSONString(map));
        channelSocketHandler.sendMessageToSessionList(new TextMessage(JSON.toJSONString(map)));
        for(Channel channel : GlobalChannel.getChannelList()){
            if(channel.getIp().equals(s) && channel.getChannel() == 1){
                if(v <= channel.getLow()){
                    addAlarmEvent(channel,v,(byte)1,"低限");
                }
                if(v >= channel.getHigh()){
                    addAlarmEvent(channel,v,(byte)1,"高限");
                }
            }
            if(channel.getIp().equals(s) && channel.getChannel() == 2){
                if(v1 <= channel.getLow()){
                    addAlarmEvent(channel,v1,(byte)2,"低限");
                }
                if(v1 >= channel.getHigh()){
                    addAlarmEvent(channel,v1,(byte)2,"高限");
                }
            }
            if(channel.getIp().equals(s) && channel.getChannel() == 3){
                if(v2 <= channel.getLow()){
                    addAlarmEvent(channel,v2,(byte)3,"低限");
                }
                if(v2 >= channel.getHigh()){
                    addAlarmEvent(channel,v2,(byte)3,"高限");
                }
            }
            if(channel.getIp().equals(s) && channel.getChannel() == 4){
                if(v3 <= channel.getLow()){
                    addAlarmEvent(channel,v3,(byte)4,"低限");
                }
                if(v3 >= channel.getHigh()){
                    addAlarmEvent(channel,v3,(byte)4,"高限");
                }
            }
        }
    }

public void addAlarmEvent(Channel channel,float val,byte channel_number, String limit)
{
    AlarmEvent a = new AlarmEvent();
    a.setUnix_time((int)(System.currentTimeMillis()/1000));
    a.setDevice_name(channel.getName());
    a.setDevice_ip(channel.getIp());
    a.setChannel_number(channel_number);
    a.setUnit(channel.getUnit());
    if(channel.getType() == 0) a.setAlarm_type("水位-"+limit);
    else if(channel.getType() == 1) a.setAlarm_type("水压-"+limit);
    else a.setAlarm_type("未知");
    a.setAlarm_data(String.valueOf(val));
    Device deviceFind = new Device();
    deviceFind.setDevice_name(channel.getName());
    deviceFind.setDevice_ip(channel.getIp());
    Device device = deviceService.findAllByNameAndIp(deviceFind);
    if(device != null){
        MapPos mapPos = new MapPos();
        mapPos.setDevice_id(device.getId());
        mapPos.setCh_x(channel_number);
        mapPos.setGeo_building_id(channel.getGeo_id());
        List<MapPos> recList = mapPosService.findRecordByClass(mapPos);
        if(recList.size() != 0) a.setMonitor_name(recList.get(0).getName());
   /*     MapPos rec = mapPosService.findRecordByClass(mapPos).get(0);
        if(rec != null) a.setMonitor_name(rec.getName());*/
    }
    AlarmEvent geo = getGeoInfor(channel);
    a.setArea(geo.getArea());
    a.setBuilding(geo.getBuilding());
    a.setFloor(geo.getFloor());
    try {
        alarmEventService.insertRecord(a);
    }catch (Exception e){
        e.printStackTrace();
    }
}

public AlarmEvent getGeoInfor(Channel channel)
{
    AlarmEvent a = new AlarmEvent();
    GeoBuilding geoA = geoBuildingService.findRecordById(channel.getGeo_id());
    if(geoA == null){
        a.setArea("无数据");
        a.setBuilding("无数据");
        a.setFloor("无数据");
    }else{
        if(geoA.getLevel() == 1) a.setArea(geoA.getName());
        if(geoA.getLevel() == 2){
            a.setBuilding(geoA.getName());
            GeoBuilding geoB = geoBuildingService.findRecordById(geoA.getParent_id());
            if(geoB != null) {
                a.setArea(geoB.getName());
            }else{
                a.setArea("无数据");
            }
        }
        if(geoA.getLevel() == 3){
            a.setFloor(geoA.getName());
            GeoBuilding geoB = geoBuildingService.findRecordById(geoA.getParent_id());
            if(geoB != null){
                a.setBuilding(geoB.getName());
                GeoBuilding geoC = geoBuildingService.findRecordById(geoB.getParent_id());
                if(geoC != null) {
                    a.setArea(geoC.getName());
                }else{
                    a.setArea("无数据");
                }
            }else{
                a.setBuilding("无数据");
            }
        }
    }
    return a;
}

    public void onLine(String s, boolean b)
    {
        System.out.println("online回调"+ b);
        if(b)
        {
            GlobalDevice.addIp(s);
            System.out.println("上线：" + s );
            deviceSocketHandler.sendMessageToSessionList(new TextMessage("ADD"));
        }
        else
        {
            GlobalDevice.removeIp(s);
            System.out.println("断线：" + s );
            deviceSocketHandler.sendMessageToSessionList(new TextMessage("REMOVE"));
            GlobalChannelData.setChannelDataStr(JSON.toJSONString(null));

            GlobalData.removeData(s);

        }
    }

    @PostConstruct
    public void start()
    {
        System.out.println("####################################################");
        System.out.println("系统启动。。。。。。");
        System.out.println("####################################################");

        List<Channel> channelList = channelService.findAllRecord();
        if(channelList.size() != 0) GlobalChannel.setChannelList(channelList);
    }

    @PreDestroy
    public void stop()
    {
        ModBusManager.getInstance().release();
    }

    //s:连接超时IP，s1:错误信息
    public void fail(String s, String s1)
    {
        System.out.println("连接错误并移除设备：" + s +"::"+s1);
    /*    System.out.println("连接错误并移除设备：" + s +"::"+s1);
        ModBusManager.getInstance().removeDevice(s);
        ModBusDevice modBusDevice = new ModBusDevice(s,502, GlobalTime.getTime());
        modBusDevice.setAddress((byte)1);
        ModBusManager.getInstance().addDevice(modBusDevice);*/
    }
}
